package com.chen.api;

import com.chen.entity.AccountB;
import com.chen.exception.MyRpcException;
import com.chen.service.AccountBService;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

public class AccountBDubboServiceImpl implements IAccountBDubboService {
    @Autowired
    private AccountBService accountBService;

    @Override
    @HmilyTCC(confirmMethod = "confirmRmbToDollar",cancelMethod = "cancelRmbToDollar")
    @Transactional(rollbackFor = Exception.class)
    public void rmbToDollar(int userId, BigDecimal rmb) throws MyRpcException {
        //准备数据
        AccountB accountB = accountBService.getByUserId(userId);
        if (accountB == null){
            throw new MyRpcException("账户B不存在");
        }
        if (accountB.getRmb().compareTo(rmb) == -1){
            throw new MyRpcException("账户B人民币金额小于转出金额");
        }
        //资金冻结
        int rows = accountBService.frozenRmbAmount(userId,rmb);
        if (rows != 1){
            throw new MyRpcException("资金冻结异常");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void confirmRmbToDollar(int userId, BigDecimal rmb) throws MyRpcException{
        accountBService.commitRmbToRmb(userId,rmb);
    }

    @Transactional(rollbackFor = Exception.class)
    public void cancelRmbToDollar(int userId, BigDecimal rmb) throws MyRpcException{
        accountBService.cancelRmbToRmb(userId,rmb);
    }
}
